package com.aiti.lulian.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.LuLianDockingMeetingPurchaserSignupInformationDto;
import com.aiti.lulian.dto.LuLianDockingMeetingSignupInformationDto;
import com.aiti.lulian.entity.LuLianDockingMeetingDetails;
import com.aiti.lulian.entity.LuLianDockingMeetingPurchaserPurchaseItem;
import com.aiti.lulian.entity.LuLianDockingMeetingPurchaserSignupInformation;
import com.aiti.lulian.entity.LuLianDockingMeetingSignupInformation;
import com.aiti.lulian.service.ILuLianDockingMeetingPurchaserPurchaseItemService;
import com.aiti.lulian.service.ILuLianDockingMeetingPurchaserSignupService;
import com.aiti.lulian.service.ILuLianDockingMeetingSignupService;
import com.aiti.lulian.utils.ActivityCaiGouExcel;
import com.aiti.lulian.utils.ActivityGongYingExcel;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jsoup.helper.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author WongMZ
 * @CreateDate 2024-07-08
 * @Description: LuLianDockingMeetingSignup控制类
 */
@RestController
@RequestMapping("/meetingSignup")
@Api(tags = "luLianDockingMeetingSignupController", description = "luLianDockingMeetingSignup控制层")
public class LuLianDockingMeetingSignupController extends WebController {

    protected final Logger logger = LoggerFactory.getLogger(LuLianDockingMeetingDetailsController.class);

    @Autowired
    private ILuLianDockingMeetingSignupService dockingMeetingSignupService;

    @Autowired
    private ILuLianDockingMeetingPurchaserSignupService dockingMeetingPurchaserSignupService;

    @Autowired
    private ILuLianDockingMeetingPurchaserPurchaseItemService purchaserPurchaseItemService;

    @ApiOperation(value = "线下活动供应商提交报名信息")
    @PostMapping
    public Message addSignupInformation(@RequestBody LuLianDockingMeetingSignupInformation signupInformation) {
        try {
            if (signupInformation == null || BeanUtil.isEmpty(signupInformation)) {
                logger.error("新增异常：===》入参异常");
                return Error("入参异常");
            }

            String userId = findUserId();
            if (userId != null) {
                signupInformation.setCreator(userId);
            } else {
                System.out.println("------------------未注册------------------");
                return Message.fail("请注册登录！");
            }

            if (StrUtil.isBlank(signupInformation.getEnterpriseName()) || StrUtil.isBlank(signupInformation.getIndustryDictFirst())
                    || StrUtil.isBlank(signupInformation.getProvince()) || StrUtil.isBlank(signupInformation.getCity())
                    || StrUtil.isBlank(signupInformation.getCounty()) || StrUtil.isBlank(signupInformation.getAddress())
                    || StrUtil.isBlank(signupInformation.getPrincipalName()) || StrUtil.isBlank(signupInformation.getPosition())
                    || StrUtil.isBlank(signupInformation.getPrincipalTel()) || StrUtil.isBlank(signupInformation.getProductPresentation())) {
                return Message.fail("带*标的字段为必填字段！");
            }

            int res = dockingMeetingSignupService.addSignupInformation(signupInformation);
            if (res > 0) {
                return Message.success();
            } else {
                return Message.fail();
            }
        } catch (Exception e) {
            logger.error("新增异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    @ApiOperation(value = "线下活动采购商提交报名信息")
    @PostMapping("/purchaser")
    public Message addPurchaserSignupInformation(@RequestBody LuLianDockingMeetingPurchaserSignupInformationDto signupInformationDto) {
        try {
            if (signupInformationDto == null || BeanUtil.isEmpty(signupInformationDto)) {
                logger.error("新增异常：===》入参异常");
                return Error("入参异常");
            }

            String userId = findUserId();
            if (userId != null) {
                signupInformationDto.setCreator(userId);
            } else {
                System.out.println("------------------未注册------------------");
                return Message.fail("请注册登录！");
            }

            if (StrUtil.isBlank(signupInformationDto.getEnterpriseName()) || StrUtil.isBlank(signupInformationDto.getIndustryDictFirst())
                    || StrUtil.isBlank(signupInformationDto.getProvince()) || StrUtil.isBlank(signupInformationDto.getCity())
                    || StrUtil.isBlank(signupInformationDto.getCounty()) || StrUtil.isBlank(signupInformationDto.getAddress())
                    || StrUtil.isBlank(signupInformationDto.getPrincipalName()) || StrUtil.isBlank(signupInformationDto.getPosition())
                    || StrUtil.isBlank(signupInformationDto.getPrincipalTel())) {
                return Message.fail("带*标的字段为必填字段！");
            }

            int res = dockingMeetingPurchaserSignupService.addPurchaserSignupInformation(signupInformationDto);
            if (res > 0) {
                return Message.success();
            } else {
                return Message.fail();
            }
        } catch (Exception e) {
            logger.error("新增异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    @ApiOperation(value = "查询我（作为供应商）报名的线下活动列表")
    @GetMapping("/supplier/list")
    public Message querySignedUpMeetingListPage(@RequestParam("pageNum") String pageNum,
                                                @RequestParam("pageSize") String pageSize,
                                                @RequestParam(value = "activityName", required = false) String activityName) {
        try {
            if (StrUtil.isBlank(pageNum) || StrUtil.isBlank(pageSize)) {
                logger.error("查询异常：===》入参异常");
                return Error("入参异常");
            }
            String userId = findUserId();
            Integer num = Integer.valueOf(pageNum);
            Integer size = Integer.valueOf(pageSize);
            List<LuLianDockingMeetingDetails> list = dockingMeetingSignupService.querySignedUpMeetingListPage(num, size, userId, activityName);
            if (list.size() > 0) {
                return Message.success(getPageResult(list, num, size, list.size()));
            } else {
                return Message.success(new ArrayList<>());
            }
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    @ApiOperation(value = "查询我（作为采购商）报名的线下活动列表")
    @GetMapping("/purchaser/list")
    public Message queryPurchaserSignedUpMeetingListPage(@RequestParam("pageNum") String pageNum,
                                                @RequestParam("pageSize") String pageSize,
                                                @RequestParam(value = "activityName", required = false) String activityName) {
        try {
            if (StrUtil.isBlank(pageNum) || StrUtil.isBlank(pageSize)) {
                logger.error("查询异常：===》入参异常");
                return Error("入参异常");
            }
            String userId = findUserId();
            Integer num = Integer.valueOf(pageNum);
            Integer size = Integer.valueOf(pageSize);
            List<LuLianDockingMeetingDetails> list = dockingMeetingPurchaserSignupService.queryPurchaserSignedUpMeetingListPage(num, size, userId, activityName);
            if (list.size() > 0) {
                return Message.success(getPageResult(list, num, size, list.size()));
            } else {
                return Message.success(new ArrayList<>());
            }
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    @ApiOperation(value = "根据baseId查询线下活动供应商报名的详细信息")
    @GetMapping("/supplier/{baseId}")
    public Message querySupplierSignupDetails(@PathVariable("baseId") String baseId) {
        try {
            if (StrUtil.isBlank(baseId)) {
                logger.error("查询异常：===》入参异常");
                return Error("入参异常");
            }
            return Message.success(dockingMeetingSignupService.getById(baseId));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    @ApiOperation(value = "根据baseId查询线下活动采购商报名的详细信息")
    @GetMapping("/purchaser/{baseId}")
    public Message queryPurchaserSignupDetails(@PathVariable("baseId") String baseId) {
        try {
            if (StrUtil.isBlank(baseId)) {
                logger.error("查询异常：===》入参异常");
                return Error("入参异常");
            }
            LuLianDockingMeetingPurchaserSignupInformation information = dockingMeetingPurchaserSignupService.getById(baseId);
            LambdaQueryWrapper<LuLianDockingMeetingPurchaserPurchaseItem> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LuLianDockingMeetingPurchaserPurchaseItem::getPurchaserSignupId, baseId);
            List<LuLianDockingMeetingPurchaserPurchaseItem> list = purchaserPurchaseItemService.list(wrapper);
            information.setItemList(list);
            return Message.success(information);
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    @ApiOperation(value = "查询用户报名线下活动的各种计数统计")
    @GetMapping("/queryCount/{userId}")
    public Message queryCount(@PathVariable("userId") String userId) {
        try {
            if (StrUtil.isBlank(userId)) {
                logger.error("查询异常：===》入参异常");
                return Message.fail("入参异常");
            }
            return Message.success(dockingMeetingSignupService.queryCount(userId));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "根据baseId修改线下活动供应商报名的详细信息")
    @PutMapping("/supplier")
    public Message updateSupplierSignupDetails(@RequestBody LuLianDockingMeetingSignupInformation signupInformation) {
        try {
            if (signupInformation == null || BeanUtil.isEmpty(signupInformation)) {
                logger.error("更新异常：===》入参异常");
                return Error("入参异常");
            }

            String userId = findUserId();
            if (StrUtil.isNotBlank(userId)) {
                signupInformation.setUpdateBy(userId);
            } else {
                System.out.println("------------------未注册------------------");
                return Message.fail("请注册登录！");
            }

            if (StrUtil.isBlank(signupInformation.getEnterpriseName()) || StrUtil.isBlank(signupInformation.getIndustryDictFirst())
                    || StrUtil.isBlank(signupInformation.getProvince()) || StrUtil.isBlank(signupInformation.getCity())
                    || StrUtil.isBlank(signupInformation.getCounty()) || StrUtil.isBlank(signupInformation.getAddress())
                    || StrUtil.isBlank(signupInformation.getPrincipalName()) || StrUtil.isBlank(signupInformation.getPosition())
                    || StrUtil.isBlank(signupInformation.getPrincipalTel()) || StrUtil.isBlank(signupInformation.getProductPresentation())) {
                return Message.fail("带*标的字段为必填字段！");
            }

            int res = dockingMeetingSignupService.updateSignupInformation(signupInformation);
            if (res > 0) {
                return Message.success();
            } else {
                return Message.fail();
            }
        } catch (Exception e) {
            logger.error("更新异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    @ApiOperation(value = "根据baseId修改线下活动采购商报名的详细信息")
    @PutMapping("/purchaser")
    public Message updatePurchaserSignupDetails(@RequestBody LuLianDockingMeetingPurchaserSignupInformationDto signupInformationDto) {
        try {
            if (signupInformationDto == null || BeanUtil.isEmpty(signupInformationDto)) {
                logger.error("更新异常：===》入参异常");
                return Error("入参异常");
            }

            String userId = findUserId();
            if (StrUtil.isNotBlank(userId)) {
                signupInformationDto.setUpdateBy(userId);
            } else {
                System.out.println("------------------未注册------------------");
                return Message.fail("请注册登录！");
            }

            if (StrUtil.isBlank(signupInformationDto.getEnterpriseName()) || StrUtil.isBlank(signupInformationDto.getIndustryDictFirst())
                    || StrUtil.isBlank(signupInformationDto.getProvince()) || StrUtil.isBlank(signupInformationDto.getCity())
                    || StrUtil.isBlank(signupInformationDto.getCounty()) || StrUtil.isBlank(signupInformationDto.getAddress())
                    || StrUtil.isBlank(signupInformationDto.getPrincipalName()) || StrUtil.isBlank(signupInformationDto.getPosition())
                    || StrUtil.isBlank(signupInformationDto.getPrincipalTel())) {
                return Message.fail("带*标的字段为必填字段！");
            }

            int res = dockingMeetingPurchaserSignupService.updatePurchaserSignupInformation(signupInformationDto);
            if (res > 0) {
                return Message.success();
            } else {
                return Message.fail();
            }
        } catch (Exception e) {
            logger.error("更新异常：===》" + e);
            return Error(e.getMessage());
        }
    }



    /**
     * 查询供应商报名
     * @return
     */
    @GetMapping("/queryGongYingShangBaoMingList")
    public Message queryGongYingShangBaoMingList(LuLianDockingMeetingSignupInformationDto gongYingShangDto){
        String userId = findUserId();
        Integer pageSize = gongYingShangDto.getPageSize();
        Integer pageNum = gongYingShangDto.getPageNum();
        Page<LuLianDockingMeetingSignupInformation> page = startPage(pageNum, pageSize);
        List<LuLianDockingMeetingSignupInformation> list = dockingMeetingSignupService.queryGongYingShangBaoMingList(page,gongYingShangDto,userId);
        return this.Success(this.getPageResult(list, pageNum, pageSize, (int)page.getTotal()));
    }

    /**
     * 查询采购商报名
     * @return
     */
    @GetMapping("/queryCaiGouShangBaoMingList")
    public Message queryCaiGouShangBaoMingList(LuLianDockingMeetingPurchaserSignupInformationDto caiGouShang){
        String userId = findUserId();
        Integer pageSize = caiGouShang.getPageSize();
        Integer pageNum = caiGouShang.getPageNum();
        Page<LuLianDockingMeetingPurchaserSignupInformation> page = startPage(pageNum, pageSize);
        List<LuLianDockingMeetingPurchaserSignupInformation> list = dockingMeetingPurchaserSignupService.queryCaiGouShangBaoMingList(page,caiGouShang,userId);
        return this.Success(this.getPageResult(list, pageNum, pageSize, (int)page.getTotal()));
    }

    /**
     * 导出企业名单
     * @param params 前端传来的参数
     */
    @GetMapping("exportCompanyInfo")
    public void exportCompanyInfo(@RequestParam  Map<String,String> params, HttpServletResponse response){
        //供应商还是采购商
        String type = params.get("type");
        //审核状态
        String status = params.get("status");

        String meetingId = params.get("meetingId");

        if(StringUtil.isBlank(status) || StringUtil.isBlank(type)){
            throw new RuntimeException("缺少参数");
        }

        if(StringUtil.isBlank(meetingId)){
            throw new RuntimeException("请选择活动");
        }

        try(ServletOutputStream outputStream = response.getOutputStream()){
            //采购商
            if(StringUtils.equals(type,"1")){
                List<LuLianDockingMeetingPurchaserSignupInformation> list = dockingMeetingPurchaserSignupService.selectCaiGouShangList(status,meetingId);
//                EasyExcel.write(outputStream,LuLianDockingMeetingPurchaserSignupInformation.class).sheet("数据").doWrite(list);
                ActivityCaiGouExcel.excelList(response,list);
            }else if(StringUtils.equals(type,"2")){
                //供应商
                List<LuLianDockingMeetingSignupInformation> list =dockingMeetingSignupService.selectGongYingShangList(status,meetingId);
//                EasyExcel.write(outputStream,LuLianDockingMeetingSignupInformation.class).sheet("数据").doWrite(list);
                ActivityGongYingExcel.excelList(response,list);
            }else{
                throw new RuntimeException("导出类型选择有误");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 供应端审核
     * @param id
     * @param status
     * @return
     */
    @GetMapping("/checkGongYingShang")
    public Message checkGongYingShang(@RequestParam("id") String id,@RequestParam("status") String status,@RequestParam(value = "bhYy",required = false) String bhYy){
        return dockingMeetingSignupService.checkGongYingShang(id,status,bhYy);
    }

    /**
     * 采购端审核
     * @param id
     * @param status
     * @return
     */
    @GetMapping("/checkCaiGouShang")
    public Message checkCaiGouShang(@RequestParam("id") String id,@RequestParam("status") String status,@RequestParam(value = "bhYy",required = false) String bhYy){
        return dockingMeetingPurchaserSignupService.checkCaiGouShang(id,status,bhYy);
    }

    /**
     * 通过Id查询供应端
     * @param id
     * @return
     */
    @GetMapping("queryGongYingDetail")
    public Message queryGongYingDetail(@RequestParam("id") String id){
        LuLianDockingMeetingSignupInformation byId = dockingMeetingSignupService.selectInfoById(id);
        return Message.success(byId);
    }

    /**
     * 通过Id查询采购端
     * @param id
     * @return
     */
    @GetMapping("queryCaiGouDetail")
    public Message queryCaiGouDetail(@RequestParam("id") String id){
        LuLianDockingMeetingPurchaserSignupInformation byId = dockingMeetingPurchaserSignupService.selectInfoById(id);

        return Message.success(byId);
    }

    @PutMapping("updateGongYingDetail")
    public Message updateGongYingDetail(@RequestBody LuLianDockingMeetingSignupInformation gongYingDetail){
        dockingMeetingSignupService.updateById(gongYingDetail);
        return Message.success();
    }

    @PutMapping("updateCaiGouDetail")
    public Message updateCaiGouDetail(@RequestBody LuLianDockingMeetingPurchaserSignupInformationDto caiGouShang){
        dockingMeetingPurchaserSignupService.updateCaiGouDetail(caiGouShang);
        return Message.success();
    }
}